var express = require('express');
var router = express.Router();
var fs = require('fs');
var { resolve } = require('path');
var session = require('express-session');

router.use(session({
  secret: 'keyboard cat',
  resave: false,
  saveUninitialized: true,
  // cookie: ('name', 'value', {
  //   maxAge: 60000,
  //   secure: false
  // })
}));

/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', { title: 'Express' });
});

// 检验是否已经登录，如果没有登录，则转到登录页面
router.get('/checklogin', (req, res) => {
  // let cookie = req.cookies.userName;
  let userInfo = req.session.userInfo;
  if (!userInfo) {
    res.send('alert("请登录以后再操作！");location.href = "./login.html"');
  } else {
    res.send('window.userInfo = "' + userInfo + '";');
  }
});

router.post('/login', (req, res) => {
  let user = req.body.username;
  let pass = req.body.password;

  let fsuser = resolve(__dirname, '../public/data/user.json');
  let users = JSON.parse(fs.readFileSync(fsuser).toString('utf-8'));

  for (var i = 0; i < users.length; i++) {
    if (users[i].username === user && users[i].password === pass) {
      // res.cookie('userName', user, {
      //   httpOnly: true,
      //   maxAge: 30000
      // });
      req.session.userInfo = user;
      res.send({
        code: 0,
        msg: 'ok'
      });
      break;
    }
  }
  if (i === users.length) {
    res.send({
      code: 1,
      msg: 'error'
    });
  }

  res.end();
});

module.exports = router;
